#import "FDScoreCardView.h"

@implementation FDScoreCardView

-(id)initWithFrame:(struct CGRect)frame {
	if ((self == [super initWithFrame: frame]) != nil) 
	{
		NSLog(@"%s ScoreCardView", _cmd);
		defaults = [[FDDefaultsController alloc] init];
		
		_contentRect = [UIHardware fullScreenApplicationContentRect];
		_offScreenRect = frame;
		_onScreenRect = frame;
		_onScreenRect.origin.y = 95.0f;
		
		UIImageView *background = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,frame.size.width,frame.size.height)];
		[background setImage:[UIImage applicationImageNamed:@"scorecard.png"]];	
		[self addSubview:background];
		[background release];
		
		UITextLabel	*cardLabel = [[UITextLabel alloc] initWithFrame:CGRectMake(22, 8, 270, 35)];	
		[cardLabel setText:@"Score Card"];
		[cardLabel setCentersHorizontally:YES];
		[cardLabel setShadowOffset:CGSizeMake(0,1)];
		
		struct __GSFont *complFont = [NSClassFromString(@"WebFontCache") createFontWithFamily:@"Georgia" traits:2 size:20];
		[cardLabel setFont:complFont];
		
		float _clearColor[4] = {1, 1, 1, 0};
		[cardLabel setBackgroundColor: CGColorCreate(CGColorSpaceCreateDeviceRGB(), _clearColor)];
		[self addSubview:cardLabel];
		[cardLabel release]; // release it

		UIView	*line = [[UIView alloc] initWithFrame:CGRectMake(22,44,270,1)];

		float _blackColor[4] = {0, 0, 0, 1};
		[line setBackgroundColor: CGColorCreate(CGColorSpaceCreateDeviceRGB(), _blackColor)];
		[self addSubview:line];
		[line release];// release it

		[self createScoreCardTable];
		[self setNewCard:YES];
	}
	return self;
}

#pragma mark Show and Hide Methods
- (void)show
{
	translate = [[UITransformAnimation alloc] initWithTarget:self];
	animator = [[UIAnimator alloc] init];

	struct CGAffineTransform trans = CGAffineTransformMakeTranslation(0, -_offScreenRect.size.height);
	
	[self setFrame:_offScreenRect];
	[translate setStartTransform:CGAffineTransformMake(1,0,0,1,0,0)];
	[translate setEndTransform:trans];
	[animator addAnimation:translate withDuration:.4 start:YES];
}

- (void)hide
{
	translate = [[UITransformAnimation alloc] initWithTarget:self];
	animator = [[UIAnimator alloc] init];
	
	struct CGAffineTransform trans = CGAffineTransformMakeTranslation(0, -_offScreenRect.size.height);
	
	[self setFrame:_onScreenRect];
	[translate setStartTransform:trans];
	[translate setEndTransform:CGAffineTransformMake(1,0,0,1,0,0)];
	[animator addAnimation:translate withDuration:.4 start:YES];
}

- (void)loadSavedGame
{
	[_scoreCardScores removeAllObjects];
	NSArray	*ta = [[NSArray alloc] initWithArray:[defaults scores]];
 	int	scoreCount = [ta count];
	int i;
	for(i = 0; i < scoreCount; ++i)
	{
		[_scoreCardScores addObject:[ta objectAtIndex:i]];
	}
	[ta release];
	
	[self setAces:[[_scoreCardScores objectAtIndex:0] intValue]];
	[self setTwos:[[_scoreCardScores objectAtIndex:1] intValue]];
	[self setThrees:[[_scoreCardScores objectAtIndex:2] intValue]];
	[self setFours:[[_scoreCardScores objectAtIndex:3] intValue]];
	[self setFives:[[_scoreCardScores objectAtIndex:4] intValue]];
	[self setSixes:[[_scoreCardScores objectAtIndex:5] intValue]];
	[self setUppersub:[[_scoreCardScores objectAtIndex:6] intValue]];
	[self setUpperbonus:[[_scoreCardScores objectAtIndex:7] intValue]];
	[self setUpperscore:[[_scoreCardScores objectAtIndex:8] intValue]];
	[self setThreeofakind:[[_scoreCardScores objectAtIndex:9] intValue]];
	[self setFourofakind:[[_scoreCardScores objectAtIndex:10] intValue]];
	[self setFullhouse:[[_scoreCardScores objectAtIndex:11] intValue]];
	[self setSmallstraight:[[_scoreCardScores objectAtIndex:12] intValue]];
	[self setLargestraight:[[_scoreCardScores objectAtIndex:13] intValue]];
	[self setYahtzee:[[_scoreCardScores objectAtIndex:14] intValue]];
	[self setChance:[[_scoreCardScores objectAtIndex:15] intValue]];
	[self setYahtzeechips:[[_scoreCardScores objectAtIndex:16] intValue]];
	[self setLowerscore:[[_scoreCardScores objectAtIndex:17] intValue]];
	[self setGrandtotal:[[_scoreCardScores objectAtIndex:18] intValue]];
	
	[_scoreCardEnabledFlags removeAllObjects];
	NSArray	*tb = [[NSArray alloc] initWithArray:[defaults scoresSet]];
 	int	setCount = [tb count];
	int j;
	for(j = 0; j < setCount; ++j)
	{
		[_scoreCardEnabledFlags addObject:[tb objectAtIndex:j]];
	}
	[tb release];
	
	[self reloadData];
	[self setNewCard:NO];
}


- (void)createScoreCardTable {
		UITableColumn *titles = [[UITableColumn alloc]
			initWithTitle:@"Titles"
			identifier:@"titles"
			width:220];
			
		UITableColumn *scores = [[UITableColumn alloc]
			initWithTitle:@"Scores"
			identifier:@"scores"
			width:50];
				 
		NSLog(@"Score Card >> init table...");
		_scoreCardTable = [[UITable alloc] initWithFrame:CGRectMake(22, 45, 270, 243)];
		[_scoreCardTable addTableColumn: titles];
		[_scoreCardTable addTableColumn: scores];
		[_scoreCardTable setSeparatorStyle:1];
		[_scoreCardTable setDelegate: self];
		[_scoreCardTable setDataSource: self];
		[_scoreCardTable setRowHeight:40.0];

		float _clearColor[4] = {1, 1, 1, 0};
		[_scoreCardTable setBackgroundColor: CGColorCreate(CGColorSpaceCreateDeviceRGB(), _clearColor)];

		_scoreCardEnabledFlags = [[NSMutableArray alloc] init];
		_scoreCardScores = [[NSMutableArray alloc] init];

		_scoreCardTitles = [NSArray arrayWithObjects:@"Aces:",@"Twos:",@"Threes:",@"Fours:",@"Fives:",@"Sixes:",
						@"Upper Total:",@"Bonus:",@"Upper Score:",@"3 of a kind:",@"4 of a kind:",@"Full House:",
						@"Sm Straight:",@"Lg Straight:",@"Yahtzee:",@"Chance:",@"Yahtzee Chips:",@"Lower Score:",@"GRAND TOTAL:",nil];

		[_scoreCardTitles retain]; // This seems to be needed so release in dealloc
					
		[self scoreCardFlags];
		
		[self reloadData];
				
		[self addSubview: _scoreCardTable];
		
		[titles release]; // The columns should be retained by the table, so we release them here
		[scores release];
		[_scoreCardTable release]; // AddSubView increases retain count by one, so we balance the alloc here.
}

- (void)scoreCardFlags {
	[_scoreCardEnabledFlags removeAllObjects];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
	[_scoreCardEnabledFlags addObject:[NSNumber numberWithBool:NO]];
}

- (int)numberOfRowsInTable: (UITable *)table
{
    return [_scoreCardTitles count];	
}

- (UITableCell *)table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col
{
	UIImageAndTextTableCell *cell = [[UIImageAndTextTableCell alloc] init];
	if (row == 6 || row == 7 || row == 8 || row == 16 || row == 17 || row == 18 || [self newCard]) {
		[cell setShowSelection:NO];
	}
	
	if ([[_scoreCardEnabledFlags objectAtIndex:row] boolValue]) {
		if (row != 6) [cell setAlpha:0.6];
		[cell setShowSelection:NO];
	}
	
	// NSLog(@"%s Row: %i  Col: %@", _cmd,row,[col identifier]);
	
	if ([[col identifier] isEqualToString:@"titles"]) {
	
		[cell setTitle:[_scoreCardTitles objectAtIndex:row]];
				
		switch (row) {
			case ACES:
			[cell setImage:[UIImage applicationImageNamed:@"ones.png"]];
			break;
			case TWOS:
			[cell setImage:[UIImage applicationImageNamed:@"twos.png"]];
			break;
			case THREES:
			[cell setImage:[UIImage applicationImageNamed:@"threes.png"]];
			break;
			case FOURS:
			[cell setImage:[UIImage applicationImageNamed:@"fours.png"]];
			break;
			case FIVES:
			[cell setImage:[UIImage applicationImageNamed:@"fives.png"]];
			break;
			case SIXES:
			[cell setImage:[UIImage applicationImageNamed:@"sixes.png"]];
			break;
			case THREEOFAKIND:
			[cell setImage:[UIImage applicationImageNamed:@"3ofakind.png"]];
			break;
			case FOUROFAKIND:
			[cell setImage:[UIImage applicationImageNamed:@"4ofakind.png"]];
			break;
			case FULLHOUSE:
			[cell setImage:[UIImage applicationImageNamed:@"fullhouse.png"]];
			break;
			case SMALLSTRAIGHT:
			[cell setImage:[UIImage applicationImageNamed:@"smstraight.png"]];
			break;
			case LARGESTRAIGHT:
			[cell setImage:[UIImage applicationImageNamed:@"lgstraight.png"]];
			break;
			case YAHTZEE:
			[cell setImage:[UIImage applicationImageNamed:@"yahtzee.png"]];
			break;
		}
	} else if ([[col identifier] isEqualToString:@"scores"]) {
		switch (row) {
			case ACES:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self aces]]];
			break;
			case TWOS:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self twos]]];
			break;
			case THREES:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self threes]]];
			break;
			case FOURS:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self fours]]];
			break;
			case FIVES:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self fives]]];
			break;
			case SIXES:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self sixes]]];
			break;
			case 6:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self uppersub]]];
			[cell setShowSelection:NO];
			break;
			case 7:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self upperbonus]]];
			[cell setShowSelection:NO];
			break;
			case 8:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self upperscore]]];
			[cell setShowSelection:NO];
			break;
			case THREEOFAKIND:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self threeofakind]]];
			break;
			case FOUROFAKIND:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self fourofakind]]];
			break;
			case FULLHOUSE:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self fullhouse]]];
			break;
			case SMALLSTRAIGHT:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self smallstraight]]];
			break;
			case LARGESTRAIGHT:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self largestraight]]];
			break;
			case YAHTZEE:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self yahtzee]]];
			break;
			case CHANCE:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self chance]]];
			break;
			case 16:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self yahtzeechips]]];
			[cell setShowSelection:NO];
			break;
			case 17:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self lowerscore]]];
			[cell setShowSelection:NO];
			break;
			case 18:
			[cell setTitle:[NSString stringWithFormat:@"%i",[self grandtotal]]];
			[cell setShowSelection:NO];
			break;
		}	
	}
	
	[cell autorelease]; // We can't keep allocing these things and not releasing them
	return cell;
}

- (void)reloadData
{
	[self updateScores];
	[_scoreCardTable reloadData];
}

- (void)tableRowSelected:(NSNotification *)notification 
{
	NSLog(@"Selected Score: %@",[_scoreCardTitles objectAtIndex:[_scoreCardTable selectedRow]]); // DEBUGGING: Used to make sure we are selecting the right row
	int row = [_scoreCardTable selectedRow];
	if (row == 6 || row == 7 || row == 8 || row == 16 || row == 17 || row == 18 || [[_scoreCardEnabledFlags objectAtIndex:row] boolValue] || [self newCard]) {
		NSLog(@"Ignored selection: %i", row);
	} else {
		//[[NSNotificationCenter defaultCenter] postNotificationName:@"scoreCardRowSelected" object:nil];
		NSLog(@"%s About to validate selected score", _cmd);
		[delegate validateScoring];
	}
}

- (void)updateScores {
	[_scoreCardScores removeAllObjects];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self aces]]];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self twos]]];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self threes]]];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self fours]]];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self fives]]];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self sixes]]];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self uppersub]]];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self upperbonus]]];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self upperscore]]];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self threeofakind]]];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self fourofakind]]];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self fullhouse]]];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self smallstraight]]];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self largestraight]]];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self yahtzee]]];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self chance]]];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self yahtzeechips]]];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self lowerscore]]];
	[_scoreCardScores addObject:[NSNumber numberWithInt:[self grandtotal]]];
}

- (void)clearScoreCard {
	[self setAces:0];
	[self setTwos:0];
	[self setThrees:0];
	[self setFours:0];
	[self setFives:0];
	[self setSixes:0];
	[self setThreeofakind:0];
	[self setFourofakind:0];
	[self setFullhouse:0];
	[self setSmallstraight:0];
	[self setLargestraight:0];
	[self setYahtzee:0];
	[self setChance:0];
	[self setYahtzeechips:0];
	[self setYahtzeeCount:0];
	
	[self scoreCardFlags];
	
	[self reloadData];
}

- (void)setInactiveRow:(int)row {
	NSLog(@"%s Row: %i", _cmd, row);
	[_scoreCardEnabledFlags replaceObjectAtIndex:row withObject:[NSNumber numberWithBool:YES]];
}

#pragma mark Scoring

- (void)calcUppersub {
	int t = 0;
	t = t + [self aces];
	t = t + [self twos];
	t = t + [self threes];
	t = t + [self fours];
	t = t + [self fives];
	t = t + [self sixes];
	[self setUppersub:t];
}

- (void)calcUpperbonus {
	if ([self uppersub] >= 63) {
		[self setUpperbonus:35];
	} else {
		[self setUpperbonus:0];
	}
}

- (void)calcUpperscore {
	[self setUpperscore:[self uppersub]+[self upperbonus]];
}

- (void)calcLowerscore {
	int t = 0;
	t = t + [self threeofakind];
	t = t + [self fourofakind];
	t = t + [self fullhouse];
	t = t + [self smallstraight];
	t = t + [self largestraight];
	t = t + [self yahtzee];
	t = t + [self chance];
	t = t + [self yahtzeechips]*100;
	[self setLowerscore:t];
}

- (void)calcYahtzeechips {
	int y = 0;
	y = [self yahtzeeCount];
	if (y > 1) [self setYahtzeechips:y-1];
}

- (void)calcGrandtotal {
	int t = 0;
	t = t + [self upperscore];
	t = t + [self lowerscore];
	[self setGrandtotal:t];
}

#pragma mark Accessors
- (BOOL)newCard
{
	return newCard;
}

- (void)setNewCard:(BOOL)newNewCard
{
	NSLog(@"%s", _cmd);
	newCard = newNewCard;
}

- (int)selectedRow
{
	return [_scoreCardTable selectedRow];
}

- (void)setSelectedRow:(int)newRow
{
	if (newRow != 6) {
		[_scoreCardTable selectRow:6 byExtendingSelection:NO withFade:YES];
		if (newRow <= 19) [_scoreCardTable selectRow:newRow byExtendingSelection:NO withFade:YES];
	}
}

- (void)clearSelection:(int)row {
	[_scoreCardTable selectRow:row byExtendingSelection:NO withFade:YES];
}

- (int)yahtzeeCount
{
	return _yahtzeeCount;
}

- (void)setYahtzeeCount:(int)newYahtzeeCount
{
	NSLog(@"%s %i", _cmd, newYahtzeeCount);
	_yahtzeeCount = newYahtzeeCount;
}

- (NSArray *)scoreCardScores
{
	return _scoreCardScores;
}

- (NSArray *)scoreCardSetScores
{
	return _scoreCardEnabledFlags;
}


#pragma mark Scoreing Accessors

- (int)aces
{
	return _aces;
}

- (void)setAces:(int)newAces
{
	_aces = newAces;
}

- (int)twos
{
	return _twos;
}

- (void)setTwos:(int)newTwos
{
	_twos = newTwos;
}

- (int)threes
{
	return _threes;
}

- (void)setThrees:(int)newThrees
{
	_threes = newThrees;
}

- (int)fours
{
	return _fours;
}

- (void)setFours:(int)newFours
{
	_fours = newFours;
}

- (int)fives
{
	return _fives;
}

- (void)setFives:(int)newFives
{
	_fives = newFives;
}

- (int)sixes
{
	return _sixes;
}

- (void)setSixes:(int)newSixes
{
	_sixes = newSixes;
}

- (int)threeofakind
{
	return _threeofakind;
}

- (void)setThreeofakind:(int)newThreeofakind
{
	_threeofakind = newThreeofakind;
}

- (int)fourofakind
{
	return _fourofakind;
}

- (void)setFourofakind:(int)newFourofakind
{
	_fourofakind = newFourofakind;
}

- (int)fullhouse
{
	return _fullhouse;
}

- (void)setFullhouse:(int)newFullhouse
{
	_fullhouse = newFullhouse;
}

- (int)smallstraight
{
	return _smallstraight;
}

- (void)setSmallstraight:(int)newSmallstraight
{
	_smallstraight = newSmallstraight;
}

- (int)largestraight
{
	return _largestraight;
}

- (void)setLargestraight:(int)newLargestraight
{
	_largestraight = newLargestraight;
}

- (int)yahtzee
{
	return _yahtzee;
}

- (void)setYahtzee:(int)newYahtzee
{
	_yahtzee = newYahtzee;
}

- (int)chance
{
	return _chance;
}

- (void)setChance:(int)newChance
{
	_chance = newChance;
}

- (int)yahtzeechips
{
	[self calcYahtzeechips];
	return _yahtzeechips;
}

- (void)setYahtzeechips:(int)newYahtzeechips
{
	_yahtzeechips = newYahtzeechips;
}

- (int)uppersub
{
	[self calcUppersub];
	return _uppersub;
}

- (void)setUppersub:(int)newUppersub
{
	_uppersub = newUppersub;
}

- (int)upperscore
{
	[self calcUpperscore];
	return _upperscore;
}

- (void)setUpperscore:(int)newUpperscore
{
	_upperscore = newUpperscore;
}

- (int)lowerscore
{
	[self calcLowerscore];
	return _lowerscore;
}

- (void)setLowerscore:(int)newLowerscore
{
	_lowerscore = newLowerscore;
}

- (int)upperbonus
{
	[self calcUpperbonus];
	return _upperbonus;
}

- (void)setUpperbonus:(int)newUpperbonus
{
	_upperbonus = newUpperbonus;
}

- (int)grandtotal
{
	[self calcGrandtotal];
	return _grandtotal;
}

- (void)setGrandtotal:(int)newGrandtotal
{
	_grandtotal = newGrandtotal;
}

- (void)scrollToVisible:(int)row {
	[_scoreCardTable scrollRowToVisible:row];
	[_scoreCardTable selectRow:row byExtendingSelection:NO withFade:YES scrollingToVisible:YES];
}

#pragma mark Delegate
- (id)delegate
{
	return delegate;
}

- (void)setDelegate:(id)newDelegate
{
	delegate = newDelegate;
}

#pragma mark Cleanup
-(void)dealloc {
	
	[_scoreCardEnabledFlags release];
	[_scoreCardScores release];
	[_scoreCardTitles release];
	[animator release];
	[translate release];
	[defaults release];
	[super dealloc];
}
	
@end
